<template>
  <view v-if="shenheStatus == 0" class="page">
    <view class="page-content">
      <view class="content-top">
        <image :src="asyncImgs.images.face_pay_mark" />
        <text>{{ $t('facePay.moneyCode') }}</text>
      </view>
      <view class="content-body">
        <view class="pay-code-box">
          <view class="title">{{ $t('facePay.scanToPay') }}</view>
          <view class="pay-money" v-if="routeData.money">
            <text>￥</text>
            <text>{{ routeData.money | formatNum }}</text>
          </view>
          <view class="pay-remark" v-if="routeData.remark">{{
            routeData.remark
          }}</view>
          <image :src="storePayUrl" />
          <view class="detail-side">
            <!-- <view @click="linkRoute('/face-pay/face-pay/setPrice')">{{
              $t('facePay.setMoney')
            }}</view> -->
            <view></view>
            <view @click="savePoster">{{ $t('facePay.saveCode') }}</view>
          </view>
        </view>
      </view>
      <!-- <view
        class="content-foot"
        @click="linkRoute('/face-pay/face-pay/record')"
      >
        <view>
          <image :src="asyncImgs.images.face_pay_record" />
          <text>{{ $t('facePay.record') }}</text>
        </view>
        <image :src="asyncImgs.images.face_arrow_right" mode=""></image>
      </view> -->
    </view>
    <canvas
      canvas-id="shareCanvas"
      id="shareCanvas"
      style="position: fixed; left: -100000px; width: 900px; height: 1350px"
    ></canvas>
    <canvas
      canvas-id="shareCanvasStoreName"
      style="position: fixed; left: -100000px; width: 900px; height: 1350px"
    ></canvas>
  </view>
  <Shenhe v-else-if="shenheStatus == 1"></Shenhe>
</template>

<script>
import Shenhe from '@/components/shenhe/shenhe';
export default {
  components: { Shenhe },
  data() {
    return {
      routeData: {},
      qrcodePath: '',
      posterSrc: '',
      store: {},
      storePayUrl: '', // 店铺收款码
    };
  },
  filters: {
    formatNum(num) {
      let str = String(num).replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,');
      if (str.split('.').length == 1) {
        str = str + '.00';
      }
      return str;
    },
  },
  onLoad(t) {},
  onShow() {
    try {
      const value = uni.getStorageSync('facePayData');
      if (value) {
        this.routeData = JSON.parse(value);
      }
      this.requestData();
      setTimeout(() => {
        uni.removeStorageSync('facePayData');
      }, 0);
    } catch (e) {
      // error
    }
  },
  methods: {
    // api获取收款码数据
    requestData() {
      this.$allrequest.facePay
        .getCollection({
          price: this.routeData.money ? this.routeData.money : 0,
        })
        .then(res => {
          if (!res.code && res.data) {
            this.store = res.data.store;
            this.storePayUrl = res.data.url;
            this.downloadQrcode().then(res => {
              this.drawCanvas();
            });
          }
        });
    },
    // 跳转路由
    linkRoute(path) {
      if (!path) return;
      this.$utils.toUrl(path);
    },
    // 下载图片
    downloadQrcode() {
      // http://tianxin100we10.cyyvip.com/web/uploads/images/store_1/2021-05-19/546074d0923828cdd1bd3b10f74c03f1e7b45463.jpeg
      return new Promise((resolve, reject) => {
        // let src =
        //   "http://tianxin100we10.cyyvip.com/web/uploads/images/store_1/2021-05-19/546074d0923828cdd1bd3b10f74c03f1e7b45463.jpeg";
        uni.getImageInfo({
          src: this.storePayUrl,
          success: image => {
            this.qrcodePath = image.path;
            resolve(image.path);
          },
        });
      });
    },
    // 获取字符串宽度
    getStrWidth(text) {
      const ctx = uni.createCanvasContext('shareCanvasStoreName');
      ctx.setFontSize(48);
      const metrics = ctx.measureText(text);
      return metrics.width;
    },
    // 画海报
    drawCanvas() {
      let ctx = uni.createCanvasContext('shareCanvas', this);
      let that = this;
      ctx.drawImage(this.asyncImgs.images.face_pay_bg, 0, 0, 900, 1350);
      ctx.drawImage(this.qrcodePath, 200, 570, 500, 500);
      ctx.setFontSize(48);
      ctx.setTextBaseline('top');
      // 截取商城名字，计算距离
      let storeName = this.$utils.overhideText(this.store.name, 10);
      const storeNameWidth = this.getStrWidth(storeName);
      ctx.fillText(storeName, (900 - storeNameWidth) / 2, 1124);
      ctx.draw(
        false,
        setTimeout(function () {
          uni.canvasToTempFilePath({
            canvasId: 'shareCanvas',
            success: function (res) {
              // 在H5平台下，tempFilePath 为 base64
              that.posterSrc = res.tempFilePath;
            },
            fail: function (res) {},
          });
        }, 500)
      );
    },
    // 点击保存在相册
    savePoster() {
      uni.showLoading({
        title: this.$t('facePay.saving'),
        mask: true,
      });

      let timer = setInterval(() => {
        if (this.posterSrc) {
          clearInterval(timer);
          uni.hideLoading();
          uni.getSetting({
            success: res => {
              let auths = res.authSetting;
              if (auths['scope.writePhotosAlbum']) {
                // 相册已授权
                uni.saveImageToPhotosAlbum({
                  filePath: this.posterSrc,
                  success: function () {
                    uni.showToast({
                      title: this.$t('facePay.saveToAlbum'),
                      duration: 2000,
                    });
                  },
                });
              } else {
                uni.authorize({
                  scope: 'scope.writePhotosAlbum',
                  success: () => {
                    this.savePoster();
                  },
                  fail() {
                    uni.showToast({
                      title: this.$t('login.fail'),
                      duration: 2000,
                    });
                  },
                });
              }
            },
          });
        }
      }, 500);
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  width: 100%;
  min-height: 100vh;
  background-color: #ff8f1f;

  .page-content {
    width: 702rpx;
    // height: 910px;
    background: #ffffff;
    border-radius: 14rpx;
    padding: 28rpx 30rpx;
    margin: 0 auto;

    .content-top,
    .content-foot {
      display: flex;
      align-items: center;
      padding-bottom: 25rpx;
      border-bottom: 1rpx solid #f5f5f5;

      image {
        width: 38rpx;
        height: 38rpx;
        display: block;
        margin-right: 25rpx;
      }
      text {
        font-size: 32rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #191919;
      }
    }
    .content-foot {
      padding-top: 25rpx;
      padding-bottom: 0;
      border-bottom: 0 none;
      border-top: 1rpx solid #f5f5f5;
      justify-content: space-between;
      view {
        display: flex;
        align-items: center;
      }

      image:last-child {
        width: 10rpx;
        height: 16rpx;
      }
    }
    .content-body {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 115rpx 0 92rpx 0;

      .pay-code-box {
        text-align: center;

        .title {
          font-size: 28rpx;
          font-family: PingFang SC;
          font-weight: 400;
          color: #191919;
        }

        .pay-money {
          font-size: 44rpx;
          font-family: PingFang SC;
          font-weight: 500;
          color: #191919;
          display: flex;
          justify-content: center;
          align-items: baseline;
          margin-top: 50rpx;

          text:first-child {
            line-height: 50rpx;
          }
          text:last-child {
            font-size: 62rpx;
            line-height: 1;
          }
        }

        .pay-remark {
          font-size: 28rpx;
          font-family: PingFang SC;
          font-weight: 400;
          color: #888888;
          text-align: center;
          margin: 32rpx 0 67rpx 0;
        }

        image {
          width: 350rpx;
          height: 350rpx;
          background: #f1f1f1;
          display: block;
          margin: 60rpx auto 57rpx;
        }
        .detail-side {
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 28rpx;
          font-family: PingFang SC;
          font-weight: 400;
          color: #999999;

          // view:nth-child(2) {
          //   width: 1rpx;
          //   height: 28rpx;
          //   background: #dedede;
          //   margin: 0 81rpx;
          // }
        }
      }
    }
  }
}
</style>
